<template>
    <div>
        <yh-dialog title="导入风险试算指令" :visible.sync="importDialog" :fullscreen="true" width="100%" :before-close="closeImportDialog">
            <el-button type="primary" @click="handleClick('import')">选择文件</el-button><i> {{ fileNames }} </i>
            <input type="file" accept=".xlsx" ref="importEntry" style="display: none" @change="fileOnChange" />
            <risk-table :msg="importListMsg" @getList="getList"></risk-table>
            <span style="color: red">备注：导入格式与导出模板一致</span>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="closeImportDialog"> 取 消 </el-button>
                <el-button size="mini" type="primary" @click="handleClick('confirm')" :disabled="importButtonDisabled"> 确 定 </el-button>
            </div>
        </yh-dialog>
    </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import RiskTable from '@/common/components/risk-table.vue';
import { importExcel, importExcels } from '@/utils/excel-utils';
import { getCurrentPageData, numberFormat } from '@/utils/tools';
import ETFColumnUtil from '../utils/etf-column-util';

@Component({
    name: 'RiskCalculateImport',
    components: {
        RiskTable,
    },
})
export default class RiskCalculateImport extends Vue {
    ETFColumnUtil = new ETFColumnUtil();
    @Prop()
    importDialog: boolean;

    @Prop()
    importButtonDisabled: boolean;

    fileNames: string = ''; // 上传文件名

    dataSource: any[] = [];
    pages = { currentPage: 1, pageSize: 25, total: 0 };

    // 导入信息相关
    importListMsg = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: [
            { name: '产品代码', val: 'fundCode', minWidth: 100 },
            { name: '资产单元', val: 'assetCode', minWidth: 100 },
            { name: '组合编码', val: 'fundAccountCode', minWidth: 100 },
            { name: '证券(合约|银行)代码', val: 'stockCode', minWidth: 150 },
            { name: '指令类型', val: 'instType', minWidth: 100 },
            { name: '交易所指令类型', val: 'exchangeType', minWidth: 130 },
            { name: '委托方向', val: 'orderDirection', minWidth: 100 },
            { name: '业务类型', val: 'instructionTypeName', minWidth: 100 },
            { name: '投资类型', val: 'investType', minWidth: 100 },
            {
                name: '指令(净价)价格',
                val: 'orderPrice',
                minWidth: 180,
                type: 'funcNumber',
                funcBody: value => (value != undefined ? numberFormat(value, 2) : '--'),
            },
            {
                name: '全价价格',
                val: 'fullPrice',
                minWidth: 100,
                type: 'funcNumber',
                funcBody: value => (value != undefined ? numberFormat(value, 2) : '--'),
            },
            {
                name: '指令(融出|全价)数量',
                val: 'orderAmount',
                minWidth: 180,
                type: 'funcNumber',
                funcBody: value => (value != undefined ? numberFormat(value) : '--'),
            },
            {
                name: '指令(合约|回购|存款|净价)金额',
                val: 'orderBalance',
                minWidth: 220,
                type: 'funcNumber',
                funcBody: value => (value != undefined ? numberFormat(value, 2) : '--'),
            },

            {
                name: '总应计利息',
                val: 'totalInterest',
                minWidth: 180,
                type: 'funcNumber',
                funcBody: value => (value != undefined ? numberFormat(value, 2) : '--'),
            },
            {
                name: '全价金额',
                val: 'fullBalance',
                minWidth: 220,
                type: 'funcNumber',
                funcBody: value => (value != undefined ? numberFormat(value, 2) : '--'),
            },
            {
                name: '到期收益率',
                val: 'yield',
                minWidth: 220,
                type: 'funcNumber',
                funcBody: value => (value != undefined ? numberFormat(value, 2) : '--'),
            },

            {
                name: '申购定金',
                val: 'earnestBalance',
                minWidth: 120,
                type: 'funcNumber',
                funcBody: value => (value != undefined ? numberFormat(value, 2) : '--'),
            },
            {
                name: '转入组合编码',
                minWidth: 130,
                val: 'destCombiId',
            },

            {
                name: '转入组合名称',
                minWidth: 130,
                val: 'destCombiName',
            },
            {
                name: '转入证券代码',
                minWidth: 130,
                val: 'destSecurityCode',
            },

            {
                name: '转入证券名称',
                minWidth: 130,
                val: 'destSecurityName',
            },
            {
                name: '巨额赎回',
                minWidth: 100,
                val: 'bulkType',
            },
            { name: '清算速度', val: 'clearSpeed', minWidth: 100 },
            {
                name: '卷面总额',
                val: 'stockFaceBalance',
                minWidth: 100,
                type: 'funcNumber',
                funcBody: value => (value != undefined ? numberFormat(value, 2) : '--'),
            },
            { name: '结算日期', val: 'firstSettleDate', minWidth: 100 },
            { name: '起息日', val: 'startDate', minWidth: 100 },
            { name: '到期日期', val: 'endSettleDate', minWidth: 100 },
            {
                name: '回购利率(%)',
                val: 'orderRate',
                minWidth: 100,
                type: 'funcNumber',
                funcBody: value => (value != undefined ? numberFormat(value, 2) : '--'),
            },
            { name: '存款类型', val: 'depositType', minWidth: 100 },
            {
                name: '存款利率(%)',
                val: 'depositRate',
                width: 150,
                type: 'func',
                funcBody: value => (value != undefined ? numberFormat(value, 2) : '--'),
            },
            { name: '提前支取限制', val: 'advanceLimitFlag', minWidth: 100 },
            { name: '银行间回购天数', val: 'repoDay', minWidth: 120 },
            { name: '通知天数', val: 'noticeDays', minWidth: 100 },
            { name: '期限', val: 'deadline', minWidth: 50 },
            { name: '费率', val: 'rate', minWidth: 50, type: 'func', funcBody: value => (value != undefined ? numberFormat(value, 2) : '--') },
            { name: '交易对手', val: 'opponentCode', minWidth: 80 },
            {
                name: '预估中签率',
                val: 'winningRate',
                minWidth: 110,
                type: 'funcNumber',
                funcBody: value => (value != undefined ? numberFormat(value, 2) : '--'),
            },
            { name: '投标方式', val: 'tenderWay', minWidth: 100 },
            { name: '招标标的', val: 'subject', minWidth: 100 },
            { name: '上市日期', val: 'listDate', minWidth: 100 },
            { name: '缴款日期', val: 'payDate', minWidth: 100 },
        ],
        height: '150px',
        // 隐藏页码
        hidePage: false,
        checked: { on: false, option: false },
    };
    importColumnsInst = [
        {
            title: '产品代码',
            dataIndex: 'fundCode',
        },
        {
            title: '资产单元',
            dataIndex: 'assetCode',
        },
        {
            title: '组合编码',
            dataIndex: 'fundAccountCode',
        },
        {
            title: '证券(合约|银行|金融产品)代码',
            dataIndex: 'stockCode',
        },
        {
            title: '指令类型',
            dataIndex: 'instType',
        },
        {
            title: '交易所指令类型',
            dataIndex: 'exchangeType',
        },
        {
            title: '委托方向',
            dataIndex: 'orderDirection',
        },
        {
            title: '业务类型',
            dataIndex: 'instructionTypeName',
        },
        {
            title: '投资类型',
            dataIndex: 'investType',
        },
        {
            title: '指令(净价)价格',
            dataIndex: 'orderPrice',
        },
        {
            title: '全价价格',
            dataIndex: 'fullPrice',
        },
        {
            title: '指令(融出|全价)数量',
            dataIndex: 'orderAmount',
        },
        {
            title: '指令(合约|回购|存款|净价)金额',
            dataIndex: 'orderBalance',
        },
        {
            title: '总应计利息',
            dataIndex: 'totalInterest',
        },
        {
            title: '全价金额',
            dataIndex: 'fullBalance',
        },
        {
            title: '到期收益率',
            dataIndex: 'yield',
        },
        {
            title: '申购定金',
            dataIndex: 'earnestBalance',
        },
        {
            title: '转入组合编码',
            dataIndex: 'destCombiId',
        },
        {
            title: '转入组合名称',
            dataIndex: 'destCombiName',
        },
        {
            title: '转入证券代码',
            dataIndex: 'destSecurityCode',
        },
        {
            title: '转入证券名称',
            dataIndex: 'destSecurityName',
        },
        {
            title: '巨额赎回',
            dataIndex: 'bulkType',
        },
        {
            title: '清算速度',
            dataIndex: 'clearSpeed',
        },

        {
            title: '券面总额',
            dataIndex: 'stockFaceBalance',
        },
        {
            title: '结算日期',
            dataIndex: 'firstSettleDate',
        },
        {
            title: '起息日',
            dataIndex: 'startDate',
        },
        {
            title: '到期日期',
            dataIndex: 'endSettleDate',
        },
        {
            title: '回购利率(%)',
            dataIndex: 'orderRate',
        },
        {
            title: '存款类型',
            dataIndex: 'depositType',
        },
        {
            title: '存款利率(%)',
            dataIndex: 'depositRate',
        },
        {
            title: '提前支取限制',
            dataIndex: 'advanceLimitFlag',
        },
        {
            title: '银行间回购天数',
            dataIndex: 'repoDay',
        },
        {
            title: '通知天数',
            dataIndex: 'noticeDays',
        },
        {
            title: '期限',
            dataIndex: 'deadline',
        },
        {
            title: '费率',
            dataIndex: 'rate',
        },
        {
            title: '交易对手',
            dataIndex: 'opponentCode',
        },
        {
            title: '预估中签率',
            dataIndex: 'winningRate',
        },

        {
            title: '投标方式',
            dataIndex: 'tenderWay',
        },
        {
            title: '招标标的',
            dataIndex: 'subject',
        },
        {
            title: '上市日期',
            dataIndex: 'listDate',
        },
        {
            title: '缴款日期',
            dataIndex: 'payDate',
        },
        {
            title: '支取日期',
            dataIndex: 'drawDate',
        },
        {
            title: '存单号',
            dataIndex: 'receiptNo',
        },
        {
            title: '利息金额',
            dataIndex: 'drawInterest',
        },
        {
            title: '支取类型',
            dataIndex: 'advanceType',
        },
    ];

    importPledgeColumns = [
        {
            title: '券面总额(万元)',
            dataIndex: 'totalFacePrice',
        },
        {
            title: '质押比率(%)',
            dataIndex: 'pledgeRatio',
        },

        {
            title: '质押金额(万元)',
            dataIndex: 'balance',
        },
        {
            title: '当前资金(万元)',
            dataIndex: 'totalPrice',
        },
        {
            title: '当前面值(元)',
            dataIndex: 'facePrice',
        },

        {
            title: '证券代码',
            dataIndex: 'stockCode',
        },
        {
            title: '证券名称',
            dataIndex: 'stockNameSt',
        },
        { title: '证券类别', dataIndex: 'stockTypeName', width: 120, type: 'func', funcBody: value => value || '--' },
        {
            title: '实时持仓数量',
            dataIndex: 'currentAmount',
        },
        {
            name: '产品序号',
            dataIndex: 'fundCode',
        },
        { title: '产品名称', dataIndex: 'fundName', width: 100, type: 'func', funcBody: value => value || '--' },
        { title: '组合编码', dataIndex: 'fundAcCode', minWidth: 110, type: 'func', funcBody: value => value || '--' },
        { title: '组合名称', dataIndex: 'fundAcName', minWidth: 110, type: 'func', funcBody: value => value || '--' },
        { title: '交易市场', dataIndex: 'marketName', minWidth: 110, type: 'func', funcBody: value => value || '--' },
        { title: '持仓标志', dataIndex: 'bullBearName', minWidth: 110, type: 'func', funcBody: value => value || '--' },
        { title: '投资类型', dataIndex: 'investTypeName', minWidth: 110, type: 'func', funcBody: value => value || '--' },
        { title: '发行人序号', dataIndex: 'issueCode', minWidth: 110, type: 'func', funcBody: value => value || '--' },
        { title: '发行人名称', dataIndex: 'issueName' },
        {
            title: '证券内评(恒生)',
            dataIndex: 'stockInnerGradeInfo',
        },
        {
            title: '证券外评(恒生)',
            dataIndex: 'stockOuterGradeInfo',
        },
        {
            title: '发行人内评(恒生)',
            dataIndex: 'issueInnerGradeInfo',
        },
        {
            title: '发行人外评(恒生)',
            dataIndex: 'issueOuterGradeInfo',
        },
        {
            title: '债券到期日',
            dataIndex: 'endDate',
        },
        {
            title: '托管机构',
            dataIndex: 'custodianName',
        },
        {
            title: '持仓编号',
            dataIndex: 'positionId',
        },
    ];
    importPledgeList: any[] = [];

    // ETF成分股信息表格列
    importETFColumns = this.ETFColumnUtil.importETFStockColumns;

    // ETF成分股信息
    importETFData: any[] = [];

    // 选择文件
    handleClick(action) {
        if (action === 'import') {
            let length = this.dataSource.length;
            if (length !== 0) {
                this.yh_message_warn('请关闭窗口重新导入');
                return;
            }
            let objFile: any = this.$refs.importEntry;
            objFile.click();
        } else if (action === 'confirm') {
            let data = this.dataSource;
            if (!data || data.length === 0) {
                this.yh_message_warn('请选择需要上传的条目文件');
                return;
            }
            data.forEach(v => {
                if (!v.stockCode) {
                    return;
                }
                v.reportCode = String(v.stockCode).split(' ')[0];
            });
            this.$emit('settingImportValue', data);
        }
    }

    /**
     * 文件上传改变事件
     */
    fileOnChange(e) {
        const { files } = e.target;
        if (files[0].type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
            this.yh_message_error('文件类型不正确');
            return;
        }
        let objFile: any = this.$refs.importEntry;
        let headers = [this.importColumnsInst, this.importPledgeColumns, this.importETFColumns];
        new Promise((resolve, reject) => {
            importExcels(
                e,
                headers,
                data => {
                    resolve(data);
                },
                e => {
                    console.error(e);
                    this.yh_message_error('文件类型不正确');
                    // eslint-disable-next-line prefer-promise-reject-errors
                    reject();
                }
            );
        }).then((res: any) => {
            if (res) {
                if (!this.verifyExcel(res)) {
                    this.yh_message_error('数据格式不正确或者数据为空，导入失败');
                    return;
                }

                this.dataSource = res;
                this.importListMsg.returnData.data = res[0];
                this.importListMsg.returnData.total = res[0].length;
                this.importPledgeList = res[1];
                this.$emit('getImportPledgeList', this.importPledgeList);
                this.fileNames = objFile.files[0].name;
            }
        });
    }

    // 校验导入表格是否为错误模板
    private verifyExcel(data): boolean {
        for (let i = 0; i < data[0].length; i++) {
            const element = data[0][i];
            // 所有字段都无 = 错误模板
            let flag = false;
            for (let key in element) {
                if (element[key]) {
                    return true;
                }
            }
            return flag;
        }
    }

    getList(pages: any) {
        let tableData: any[] = [];
        let dataSource = this.importListMsg.returnData.data;
        tableData = getCurrentPageData(dataSource, this.pages.currentPage, this.pages.pageSize);
        this.importListMsg.returnData.data = JSON.parse(JSON.stringify(tableData));
    }

    // 关闭对话框
    closeImportDialog() {
        this.$emit('closeImportDialog');
    }
}
</script>
<style lang="scss" scoped></style>
